package com.chooseCourses.servlet.student;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/ScheduleSelect")
public class ScheduleSelect extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");//课表id
        String userName = req.getParameter("userName");
        String userId = req.getParameter("userId");

        BaseDao baseDao = new BaseDao();
        PreparedStatement ps;
        ResultSet rs;

        String sql="select * from studentcourse where studentid =" + userId + " and scheduleId = "+id ;

        try {
            ps=baseDao.getConnection().prepareStatement(sql);
            rs = ps.executeQuery();//执行sql语句
            if(rs.next()) {//返回的是布尔值,假如返回的是true,即有数据了,就不能选择该课程,跳到过渡页No
//                PrintWriter out = resp.getWriter();
                baseDao.closeResource(null,ps,rs);// 关闭数据流
                resp.sendRedirect("student/false.jsp?userName=" + userName + "&userId=" + userId);
            }else {	//返回false,则可以选择
                // 调用db中的方法
                sql = "insert into studentcourse(studentid,scheduleid) values(?,?)";
                ps = baseDao.getConnection().prepareStatement(sql);
                // 添加数据
                ps.setString(1, userId);
                ps.setString(2, id);
                ps.executeUpdate();// 执行sql语句
//                PrintWriter out = resp.getWriter();
                resp.sendRedirect("student/true.jsp?userName=" + userName + "&useId=" + userId);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    public ScheduleSelect() {super();

    }
}
